package com.ld.security.auth.common.util;

import java.util.Date;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import lombok.SneakyThrows;

public class JwtUtil {

    // 过期时间5分钟
    private static final long EXPIRE_TIME = 5*60*1000;


    /**
     * 获得token中的信息无需secret解密也能获得
     * @return token中包含的用户名
     */
    public static String getUsername(String token) {

            DecodedJWT jwt = JWT.decode(token);
   
            
            return jwt.getClaim("username").asString();
     
    }
    
    /**
     * 对token认证
     * @param token
     * @return
     */
    public static boolean auth(String token) {
        DecodedJWT jwt = JWT.decode(token);
        Date date = jwt.getExpiresAt();
        long x = date.getTime();
        long y = System.currentTimeMillis();
        return y < x ;
    }

    @SneakyThrows
    public static void verify(String token, String username, String password) {
   
            Algorithm algorithm = null;
		
				algorithm = Algorithm.HMAC256(password);
	
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("username", username)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
        
    }
    
    /**
     * 生成签名,5min后过期
     * @param username 用户名
     * @param password 用户的密码
     * @return 加密的token
     */
    @SneakyThrows
    public static String crtToken(String username, String password) {
   
            Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(password);
            // 附带username信息
            return JWT.create()
                    .withClaim("username", username)
                    .withExpiresAt(date)
                    .sign(algorithm);
 
    }
    
    

    
    public static void main(String[] args) throws Exception {
    	String token = crtToken("ldl","ldl");
    	verify(token, "ldl", "ldl");

	}

}